var Buffer = require('buffer').Buffer;
import {OAuth2Token} from '../../src/http/oauth2-token';
import {querystring} from '../../src/http/querystring';

var passwordToken = function (body) {

	var authorities = ["auth1", "auth2", "auth3", "ROLE_role1", "ROLE_role2", "ROLE_role3"];
	var accessToken = {
		"aud": ["OUTORG", "TECSKILL", "AUTH"],
		"user_name": "1176205",
		"scope": (body['scope'] || '').split(' '),
		"exp": Math.floor(new Date().getTime()/1000 + 86400),
		"authorities": authorities,
		"jti": "cd57684b-e66b-48fc-8245-224b3c0e1ac9",
		"client_id": "client"
	}

	var accessTokenStr = 'eyJhbGciOiJTSEExd2l0aEVDRFNBIiwidHlwIjoiSldUIn0=.' +
		Buffer.from(JSON.stringify(accessToken)).toString('base64') +
		'.MIGUAkgCAzzjrpQ5ic0hMrJ4ofduimEA0anlX7bwJSLgNB17ZOwKNLxdsvlNFI7oC9mmA4RBq5SWyS+vVWihNXxbXMUrwfx2UZw4YzoCSALJvs7nnHhZ1qkF6Zi6y3vIr0Vl1VOBdQ4cjOa+XY+pvZOU+WYzN07/OapHHFYbBGnxmJy8MctEWdaR2IyeMQDlmXmnfs7WQg==';

	var refreshToken = {
		"aud": ["OUTORG", "TECSKILL", "AUTH"],
		"user_name": "1176205",
		"scope": body['scope'],
		"ati": "5b1a44a2-0186-4c46-aeab-e5abb4327c85",
		"exp": Math.floor(new Date().getTime()/1000 + 8640000),
		"authorities": authorities,
		"jti": "69b92b3c-42ce-4684-b7d9-73b9b18e2295",
		"client_id": "client"
	}

	var refreshTokenStr = 'eyJhbGciOiJTSEExd2l0aEVDRFNBIiwidHlwIjoiSldUIn0=.' +
		new Buffer(JSON.stringify(refreshToken)).toString('base64') +
		'.MIGUAkgBZ+x6slR7TYFJeyXS6PqOgIogw4E6/TL6Jy6g6n4EiztM6ELXuR7WltjnOhD8w9llYvHqBE2VUBJRr+/mEJlFu3xdJLGpepwCSANi5DZ8An6IrvXC4S0cNv42SYRdCZMufeFp53Z0D2toAfUCkcjVsfsDKQ91EAVZCgmoIwSJ5O8YrUSdWnS1TQ52MPo7UUWprA==';


	return {
		'access_token':accessTokenStr,
		'token_type': 'bearer',
		'refresh_token':refreshTokenStr,
		'expires_in': 199999,
		'scope': body['scope'],
		'jti': '5b1a44a2-0186-4c46-aeab-e5abb4327c85',
		'openid': 'kV9n1UoFd7CwGR9/3mKrSA=='
	};
}

var clientCredentialsToken = function (body) {
	var authorities = ["auth1", "auth2", "auth3", "ROLE_role1", "ROLE_role2", "ROLE_role3"];

	var accessToken = {
		"aud": ["OUTORG", "TECSKILL", "AUTH"],
		"scope": (body['scope'] || '').split(' '),
		"exp": Math.floor(new Date().getTime()/1000 + 86400),
		"authorities": authorities,
		"jti": "cd57684b-e66b-48fc-8245-224b3c0e1ac9",
		"client_id": "client"
	}

	var accessTokenStr = 'eyJhbGciOiJTSEExd2l0aEVDRFNBIiwidHlwIjoiSldUIn0=.' +
		new Buffer(JSON.stringify(accessToken)).toString('base64') +
		'.MIGUAkgCAzzjrpQ5ic0hMrJ4ofduimEA0anlX7bwJSLgNB17ZOwKNLxdsvlNFI7oC9mmA4RBq5SWyS+vVWihNXxbXMUrwfx2UZw4YzoCSALJvs7nnHhZ1qkF6Zi6y3vIr0Vl1VOBdQ4cjOa+XY+pvZOU+WYzN07/OapHHFYbBGnxmJy8MctEWdaR2IyeMQDlmXmnfs7WQg==';

	return {
		'access_token':accessTokenStr,
		'token_type': 'bearer',
		'expires_in': 199999,
		'scope': body['scope'],
		'jti': '5b1a44a2-0186-4c46-aeab-e5abb4327c85',
		'openid': 'kV9n1UoFd7CwGR9/3mKrSA=='
	};
}

//模拟 token 刷新
var refreshToken = function (body) {

	//解析刷新 token
	var token = OAuth2Token.parse(body['refresh_token'])

	var accessToken = {
		"aud": token.resourceIds,
		"user_name": token.userId,
		"scope": token.scopes,
		"exp": Math.floor(new Date().getTime()/1000 + 86400),
		"authorities": token.authorities,
		"jti": token.tokenId,
		"client_id": token.clientId,
	}

	var accessTokenStr = 'eyJhbGciOiJTSEExd2l0aEVDRFNBIiwidHlwIjoiSldUIn0=.' +
		new Buffer(JSON.stringify(accessToken)).toString('base64') +
		'.MIGUAkgCAzzjrpQ5ic0hMrJ4ofduimEA0anlX7bwJSLgNB17ZOwKNLxdsvlNFI7oC9mmA4RBq5SWyS+vVWihNXxbXMUrwfx2UZw4YzoCSALJvs7nnHhZ1qkF6Zi6y3vIr0Vl1VOBdQ4cjOa+XY+pvZOU+WYzN07/OapHHFYbBGnxmJy8MctEWdaR2IyeMQDlmXmnfs7WQg==';

	var refreshToken = {
		"aud": token.resourceIds,
		"user_name": token.userId,
		"scope": token.scopes,
		"exp": Math.floor(new Date().getTime()/1000 + 8640000),
		"authorities": token.authorities,
		"jti": token.tokenId,
		"client_id": token.clientId,
	}

	var refreshTokenStr = 'eyJhbGciOiJTSEExd2l0aEVDRFNBIiwidHlwIjoiSldUIn0=.' +
		new Buffer(JSON.stringify(refreshToken)).toString('base64') +
		'.MIGUAkgBZ+x6slR7TYFJeyXS6PqOgIogw4E6/TL6Jy6g6n4EiztM6ELXuR7WltjnOhD8w9llYvHqBE2VUBJRr+/mEJlFu3xdJLGpepwCSANi5DZ8An6IrvXC4S0cNv42SYRdCZMufeFp53Z0D2toAfUCkcjVsfsDKQ91EAVZCgmoIwSJ5O8YrUSdWnS1TQ52MPo7UUWprA==';


	return {
		'access_token':accessTokenStr,
		'token_type': 'bearer',
		'refresh_token':refreshTokenStr,
		'expires_in': 199999,
		'scope': body['scope'],
		'jti': '5b1a44a2-0186-4c46-aeab-e5abb4327c85',
		'openid': 'kV9n1UoFd7CwGR9/3mKrSA=='
	};
}

var token = async (ctx, netx) => {
	var body = ctx.request.body;
	var tokenValue = undefined;
	// var body = querystring.decode(Buffer.from(request.body).toString())
	if('password' == body['grant_type']){
		tokenValue = passwordToken(body);
	}else if('client_credentials' == body['grant_type']){
		tokenValue = clientCredentialsToken(body);
	}else if('refresh_token' == body['grant_type']){
		tokenValue = refreshToken(body);
	}

	// return tokenValue;
    ctx.set('content-type','application/json;charset=utf-8')
    //ctx.status = 404;
    ctx.response.body = JSON.stringify(tokenValue);
}

var response401 = async (ctx, next) => {

	ctx.set('content-type','application/json;charset=utf-8')
	ctx.status = 401;
	// ctx.response.body = JSON.stringify(tokenValue);
}
var response403 = async (ctx, next) => {

	ctx.set('content-type','application/json;charset=utf-8')
	ctx.status = 401;
	// ctx.response.body = JSON.stringify(tokenValue);
}

var api = async (ctx, next) =>{
	//判断是否有认证信息
	var authInfo = ctx.request.headers["authorization"];

	if(!authInfo){
		//如果没有认证信息，则返回 401
		ctx.status = 401;
		return;
	}
	var accessToken = OAuth2Token.parse(authInfo.substr(7));
	var accessToken = {
		"aud": accessToken.resourceIds,
		"user_name": accessToken.userId,
		"scope": accessToken.scopes,
		"exp": accessToken.expires.getTime()/1000,
		"authorities": accessToken.authorities,
		"jti": accessToken.tokenId,
		"client_id": accessToken.clientId,
	}

	//判断 token 类型的是正确的，只判断JWT中内容，不判断 header 和签名
	if(authInfo.substring(authInfo.indexOf('.')+1,authInfo.lastIndexOf('.')) !=
		new Buffer(JSON.stringify(accessToken)).toString('base64')){
		//如果认证信息错误，则返回 401
		ctx.status = 401;
		return;
	}
	ctx.set('content-type','application/json;charset=utf-8')
	//ctx.status = 404;
	ctx.response.body = JSON.stringify("ok");
}
// module.exports = {
//     '/oauth/token': token,
// 	'/oauth/401': response401,
// 	'/oauth/403': response403,
// 	'/oauth/api': api,
// }

module.exports =  {
	'/oauth/token': token,
	'/oauth/api': api,
}
